import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/http/index.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/routers/route.dart';
import 'package:flutter_massage/common_lib/utils/js_channel_operation.dart';
import 'package:flutter_massage/common_lib/utils/method_channel.dart';
import 'package:flutter_massage/generated/assets.dart';
import 'package:flutter_massage/pages/home/home_page.dart';
import 'package:flutter_massage/pages/login/index.dart';
import 'package:flutter_massage/pages/message/message_new_page.dart';
import 'package:flutter_massage/pages/my/my_page.dart';
import 'package:flutter_massage/pages/same_city/same_city_page.dart';
import 'package:flutter_massage/pages/technician/technician_page.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/sqlite/db_manager.dart';
import 'package:flutter_massage/values/index.dart';
import 'package:get/get.dart' hide Response;
import 'package:in_app_review/in_app_review.dart';

class MainLogic extends GetxController {
  final InAppReview inAppReview = InAppReview.instance;

  final PageController pageController = PageController();

  static const String tabHome = '首页';
  static const String tabJs = '技师';
  static const String tabTc = '同城';
  static const String tabMessage = '消息';
  static const String tabMine = '我的';

  int currentIndex = 0;
  List<BottomBarItem> items = [
    BottomBarItem(icon: Assets.svgTabHomeNormal, selectedIcon: Assets.svgTabHomeSelect, name: tabHome),
    BottomBarItem(icon: Assets.svgTabJsNormal, selectedIcon: Assets.svgTabJsSelect, name: tabJs),
    BottomBarItem(icon: Assets.svgTabTcNormal, selectedIcon: Assets.svgTabTcSelect, name: tabTc),
    BottomBarItem(icon: Assets.svgTabMessageNormal, selectedIcon: Assets.svgTabMessageSelect, name: tabMessage),
    BottomBarItem(icon: Assets.svgTabMyNormal, selectedIcon: Assets.svgTabMySelect, name: tabMine),
  ];
  List<Widget> pageList = const [HomePage(), TechnicianPage(), SameCityPage(), MessageNewPage(), MyPage()];
  bool showTabBar = true;

  void initData() async {
    ///请求设置接口
    SettingBean bean = await XydUserService.getCacheMineInfoBean(refresh: true);
    refreshPreferredUnreadNum();

    ///原生弹窗
    if (bean.box?.url.notEmpty ?? false) {
      double? width = double.tryParse(bean.box?.width ?? '');
      double? height = double.tryParse(bean.box?.height ?? '');
      CommonDialog.showBox(url: bean.box!.url!, width: width, height: height);
    }

    ///应用评分
    if (bean.rank.equals('1')) showAppInReview();

    ///构建tab
    // pageList = const [HomePage(), TechnicianPage(), SameCityPage(), MessagePage(), MyPage()];
    // items = [
    //   BottomBarItem(icon: Assets.svgTabHomeNormal, selectedIcon: Assets.svgTabHomeSelect, name: tabHome),
    //   BottomBarItem(icon: Assets.svgTabJsNormal, selectedIcon: Assets.svgTabJsSelect, name: tabJs),
    //   BottomBarItem(icon: Assets.svgTabTcNormal, selectedIcon: Assets.svgTabTcSelect, name: tabTc),
    //   BottomBarItem(icon: Assets.svgTabMessageNormal, selectedIcon: Assets.svgTabMessageSelect, name: tabMessage),
    //   BottomBarItem(icon: Assets.svgTabMyNormal, selectedIcon: Assets.svgTabMySelect, name: tabMine),
    // ];

    // if (bean.tab.equals('1')) {
    //   pageList = const [SameCityPage(), TechnicianPage(), HomePage(), MessageNewPage(), MyPage()];
    //   items = [
    //     BottomBarItem(icon: Assets.svgTabTcNormal, selectedIcon: Assets.svgTabTcSelect, name: tabTc),
    //     BottomBarItem(icon: Assets.svgTabJsNormal, selectedIcon: Assets.svgTabJsSelect, name: tabJs),
    //     BottomBarItem(icon: Assets.svgTabHomeNormal, selectedIcon: Assets.svgTabHomeSelect, name: tabHome),
    //     BottomBarItem(icon: Assets.svgTabMessageNormal, selectedIcon: Assets.svgTabMessageSelect, name: tabMessage),
    //     BottomBarItem(icon: Assets.svgTabMyNormal, selectedIcon: Assets.svgTabMySelect, name: tabMine),
    //   ];
    // }

    update();

    XydMethodChannel.nativeCallFlutter((call) async {
      if (call.method == 'parseScheme') {
        JsChannelOperation.jumpToPage(call.arguments);
      }
    });
  }

  ///显示、隐藏tabBar
  void changeTabBarVisible(bool visible) {
    showTabBar = visible;
    update();
  }

  ///好评弹窗
  void showAppInReview() async {
    if (await inAppReview.isAvailable()) inAppReview.requestReview();
  }

  ///获取优选tab未读数
  void refreshPreferredUnreadNum() async {
    String key = Storage().getString(StorageKey.userKey);
    if (key.empty) return;
    dynamic json = await CommonNet.get(ApiMine.unread());
    updateBadgeByTabName(tabName: tabMessage, badgeNum: '${json['data']['unread']}');
  }

  void updateBadgeByTabName({required String tabName, required String badgeNum}) {
    List<BottomBarItem> result = items.where((element) => element.name.equals(tabName)).toList();
    if (result.isEmpty) return;
    for (var element in result) {
      element.badgeNum = badgeNum;
    }
    update();
  }

  void onJumpToPage(String tabName) {
    // if (tabName == tabPreferred || tabName == tabShop || tabName == tabMine) {
    //   if (XydUserService.instance.xydAuth.empty) {
    //     if (tabName == tabPreferred) {
    //       CommonRoute.openLogin();
    //     } else {
    //       CommonDialog.showLoginDialog();
    //     }
    //     return;
    //   }
    // }
    int index = items.indexWhere((element) => element.name == tabName);
    if (index < 0 || index >= items.length) return;
    String uuid = XydUserService.key;
    if ((tabName.equals(tabMine) || tabName.equals(tabMessage)) && uuid.empty) {
      CommonRoute.open(const LoginPage(hideBackBtn: false));
      return;
    }
    currentIndex = index;
    pageController.jumpToPage(index);
    update();
  }

  @override
  void onReady() async {
    super.onReady();
    DbManager.openDb();
    initData();
  }

  @override
  void onClose() {
    super.onClose();
    DbManager.closeDb();
    pageController.dispose();
  }
}

class BottomBarItem {
  BottomBarItem({required this.name, required this.icon, required this.selectedIcon, this.badgeNum = '0'});

  String name;
  String badgeNum;
  String icon;
  String selectedIcon;
}
